/*
 * Created on 2005/05/09
 * Author aki@www.xucker.jpn.org
 * License Apache2.0 or Common Public License
 */
package jp.sourceforge.akjrcp.ui.draw2d;



import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.graphics.Image;

/**
 * 
 *@deprecated use com.akjava.lib.swt
 */
public class FileImageCache implements CachedImageLoader{
List<String> imageList=new ArrayList<String>();
Map<String, Image> imageMap=new HashMap<String, Image>();
int maxSize=32;

private CachedImageListener cachedImageListener;

public CachedImageListener getCachedImageListener() {
    return cachedImageListener;
}
public void setCachedImageListener(CachedImageListener cachedImageListener) {
    this.cachedImageListener = cachedImageListener;
}
public int getMaxSize() {
    return maxSize;
}
public void setMaxSize(int maxSize) {
    this.maxSize = maxSize;
}
public static Log log=LogFactory.getLog(FileImageCache.class);
private void add(Image img,String key){
//log.infoadd:"+key);
imageList.add(key);    
imageMap.put(key,img);
}

public  Image loadImage(String key){
    log.trace("call:"+key);
    Image img=(Image)imageMap.get(key);
    if(img!=null){
        log.trace("find:"+key);
        //move last
        synchronized(this){
        imageList.remove(key);
        imageList.add(key);
        }
        return img;
    }else{
        File file=new File(key);
        if(file.exists()){
            log.trace("read:"+key);
        Image newImage=null;
        try{
        newImage=new Image(null,file.getAbsolutePath());
        }catch(Exception e){
            log.warn(e);
            return null;
        }
        if(cachedImageListener!=null){
            cachedImageListener.loaded(newImage,key);
        }
        add(newImage,key);
        if(imageList.size()>maxSize){
        	synchronized(this){
        		remove((String)imageList.get(0));//remove first one
        		}
        	}
        return newImage;
        }
    }
    return null;
}
public synchronized void removeAll(){
	String[] keys=(String[]) imageMap.keySet().toArray(new String[imageMap.size()]);
	for (int i = 0; i < keys.length; i++) {
		
		remove(keys[i]);
	}
}
public void remove(String key){
    //log.inforemoved:"+key);
    Image obj=(Image)imageMap.remove(key);
    if(obj!=null){
        if(!obj.isDisposed()){
            obj.dispose();
            
        }
        log.trace("remove:"+key);
        imageList.remove(key);
    }
}

}
